package com.demo.rpc.netty.consumer.proxy;

import com.demo.rpc.netty.protocol.InvocationProtocol;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcProxy {

    public static <T> T create(Class<T> clazz) {
        MethodProxy methodProxy = new MethodProxy(clazz);
        Class<?>[] interfaces = clazz.isInterface() ? new Class<?>[]{clazz} : clazz.getInterfaces();
        T o = (T) Proxy.newProxyInstance(clazz.getClassLoader(), interfaces, methodProxy);
        return o;
    }


    private static class MethodProxy implements InvocationHandler {

        private Class<?> originClass;

        public MethodProxy(Class<?> originClass) {
            this.originClass = originClass;
        }

        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            if (Object.class.equals(method.getDeclaringClass())) {
                try {
                    return method.invoke(this, objects);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                return rpcInvoke(o, method, objects);
            }
            return null;
        }

        private Object rpcInvoke(Object proxy, Method method, Object[] args) {
            //rpc参数
            InvocationProtocol invocationProtocol = new InvocationProtocol();
            invocationProtocol.setClassName(this.originClass.getName());
            invocationProtocol.setMethodName(method.getName());
            invocationProtocol.setValues(args);
            invocationProtocol.setParams(method.getParameterTypes());
            //
            RpcProxyHandler rpcProxyHandler = new RpcProxyHandler();
            NioEventLoopGroup group = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap();
                b.group(group)
                        .channel(NioSocketChannel.class)
                        .option(ChannelOption.TCP_NODELAY, true)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                ChannelPipeline pl = socketChannel.pipeline();
                                pl.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                                pl.addLast("frameEncoder", new LengthFieldPrepender(4));
                                pl.addLast("encoder", new ObjectEncoder());
                                pl.addLast("decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                                pl.addLast("handler", rpcProxyHandler);
                            }
                        });
                ChannelFuture future = b.connect("localhost", 8080).sync();
                future.channel().writeAndFlush(invocationProtocol).sync();
                future.channel().closeFuture().sync();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                group.shutdownGracefully();
            }
            return rpcProxyHandler.getResponse();
        }
    }
}
